Fragment RootView防止Fragment不断初始化

Posted by アライさん on 2019年10月22日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public abstract class BaseFragment extends Fragment {
protected View rootView;
protected Context applicationContext;

protected abstract int getLayoutId();

protected abstract void findViewById(View view);

protected abstract void initView(Bundle savedInstanceState);

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(getLayoutId(), container, false);
applicationContext = getActivity().getApplicationContext();
findViewById(rootView);
initView(savedInstanceState);
}

ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
return rootView;
}
}